<?php
namespace app\api\Controller;

use think\Controller;
use think\Db;
// use app\home\logic\UsersLogic;

class Func extends Controller
{
    public function _initialize(){
        parent::_initialize();
    }

    /**
    *获取用户openid
    */
    public function get_openid(){
        $data = $this->request->post();
        $wechatMsg = Db::name('plugin')->field('config_value')->where('code','weixinsmall')->find();
        $wechatMsg = unserialize($wechatMsg['config_value']);
        $code = $data['code'];
        $appid = $wechatMsg['appid'];
        $appsecret = trim($wechatMsg['appsecret']);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $output = curl_exec($ch);
        curl_close($ch);
        $result_arr = json_decode($output,true);
        $result = $this->mini_login($result_arr['openid']);
        return $result;
    }

    public function mini_login($openid){
        $user = $this->get_user_info($openid);
        if(!$user){
            //新用户
            $row_id = Db::name('third_user')->insertGetId(['openid'=>$openid]);
            $user = Db::name('third_user')->where("user_id", $row_id)->find();
        }else{
            $info = Db::name('third_user')->where("openid", $openid)->update(array('last_login'=>date('Y-m-d H:i:s')));
        }
        return json(array('status'=>1,'msg'=>'登陆成功','result'=>$user));
    }

    public function get_user_info($openid = ''){
        $map = [];
        if(!empty($openid)){
            $map['openid'] = ['eq',$openid];
            $user = Db::name('third_user')->where($map)->find();
            return $user;
        }else{
            //不是微信打开的，需要绑定手机号注册
            return false;
        }

    }
}